package cn.lu.service.impl;

import cn.lu.dao.ChapterMapper;
import cn.lu.dao.CurriculumMapper;
import cn.lu.dao.SectionMapper;
import cn.lu.dao.UserCurriculumMapper;
import cn.lu.pojo.Chapter;
import cn.lu.pojo.Curriculum;
import cn.lu.pojo.Section;
import cn.lu.service.ChapterService;
import cn.lu.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ChapterServiceImpl implements ChapterService {
    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private CurriculumMapper curriculumMapper;

    @Autowired
    private SectionMapper sectionMapper;

    @Autowired
    private UserCurriculumMapper userCurriculumMapper;

    @Override
    public int addInsert(Chapter chapter) {
        if (curriculumMapper.selectByPrimaryKey(chapter.getCurriculumId()) != null) {
            return chapterMapper.insert(chapter);
        }
        return 0;
    }


    @Override
    public List<Chapter> selectByCurriculumId(Integer chapterId) {
        return chapterMapper.selectByCurriculumId(chapterId);
    }

    @Override
    public int updateById(Chapter chapter) {
        return chapterMapper.updateByPrimaryKey(chapter);
    }


    @Override
    public Result deleteByIdAndUserId(Integer chapterId, Integer userId) {
        if (sectionMapper.selectChapterId(chapterId).size() == 0) {
            if (chapterMapper.deleteByIdAndUserId(chapterId, userId) == 1) {
                return new Result().success();
            } else {
                return new Result().fail();
            }
        } else {
            return new Result().fail("请先删除小节再删除章节");
        }
    }


    @Override
    public Result updateByIdAndUserId(Chapter chapter, Integer userId) {
        if (chapterMapper.updateByIdAndUserId(chapter, userId) == 1) {
            return new Result().success();
        } else {
            return new Result().fail();
        }
    }

    @Override
    public Result addInTheUserId(Chapter chapter, Integer userId) {
        if (curriculumMapper.curriculumWhetherTeacher(chapter.getCurriculumId(), userId) == 1) {
            if (chapterMapper.insert(chapter) == 1) {
                return new Result().success();
            } else {
                return new Result().fail();
            }
        } else {
            return new Result().fail("您没有权限操作");
        }
    }
}